package socket;

import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;
import java.net.*;

@SuppressWarnings("serial")
class SocketServidor extends JFrame implements ActionListener {

	int port;

	JButton button;

	JLabel label = new JLabel("Texto recibido por el socket:");

	JPanel panel;

	JTextArea textArea = new JTextArea();

	ServerSocket server = null;

	Socket client = null;

	BufferedReader in = null;

	PrintWriter out = null;

	String line;

	SocketServidor(int port) {
		
		this.port = port;

		button = new JButton("Recibir");
		button.addActionListener(this);

		panel = new JPanel();
		panel.setLayout(new BorderLayout());
		panel.setBackground(Color.white);
		getContentPane().add(panel);
		panel.add("North", label);
		panel.add("Center", textArea);
		panel.add("South", button);

	}

	public void actionPerformed(ActionEvent event) {
		Object origen = event.getSource();

		if (origen == button) {
			textArea.setText(line);
		}
	}

	public void listenSocket() {

		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			System.out.println("No se puede escuchar en el puerto: "+ port);
			System.exit(-1);
		}

		try {
			client = server.accept();
		} catch (IOException e) {
			System.out.println("No se pudo aceptar en el puerto: "+ port);
			System.exit(-1);
		}

		try {
			in = new BufferedReader(new InputStreamReader(client
					.getInputStream()));
			out = new PrintWriter(client.getOutputStream(), true);
		} catch (IOException e) {
			System.out.println("No se pudo aceptar en el puerto: "+port);
			System.exit(-1);
		}

		while (true) {
			try {
				line = in.readLine();
				// Send data back to client
				out.println(line);
			} catch (IOException e) {
				System.out.println("Error al leer.");
				System.exit(-1);
			}
		}
	}

	protected void finalize() {
		// Clean up
		try {
			in.close();
			out.close();
			server.close();
		} catch (IOException e) {
			System.out.println("Error al cerrar.");
			System.exit(-1);
		}
	}
}
